package com.dao;

import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.FactoryBean;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory> {
    private String mybatisConfigLocation;

    public String getMybatisConfigLocation() {
        return mybatisConfigLocation;
    }

    public void setMybatisConfigLocation(String mybatisConfigLocation) {
        this.mybatisConfigLocation = mybatisConfigLocation;
    }

    @Override
    public SqlSessionFactory getObject() throws Exception {
        InputStream stream = null;
        SqlSessionFactory factory = null;
        try {
            stream = Resources.getResourceAsStream(getMybatisConfigLocation());
            factory = new SqlSessionFactoryBuilder().build(stream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new PersistenceException("创建mybatis工厂失败");
        }
        return factory;
    }

    @Override
    public Class<?> getObjectType() {
        return SqlSessionFactory.class;
    }
}
